<template>
  <div class="exhibition-container">
    <div class="header">
      <h2>展览管理</h2>
      <div class="header-actions">
        <el-switch
          v-model="debugMode"
          class="debug-switch"
          inactive-text="调试模式"
          size="small"
        />
        <el-button type="primary" @click="addExhibition">新增展览</el-button>
      </div>
    </div>
    
    <el-table
      v-loading="loading"
      :data="exhibitionList"
      style="width: 100%"
      border
    >
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="title" label="展览标题" />
      <el-table-column label="封面图" width="180">
        <template #default="scope">
          <div class="image-container">
            <el-image
              style="width: 80px; height: 80px"
              :src="getImageUrl(scope.row.cover)"
              :preview-src-list="[getImageUrl(scope.row.cover)]"
              fit="cover"
            >
              <template #error>
                <div class="image-error">
                  <el-icon><icon-picture /></el-icon>
                  <p class="small-text">加载失败</p>
                </div>
              </template>
            </el-image>
            <div class="image-debug" v-if="debugMode">
              <p>源路径: {{ scope.row.cover }}</p>
              <p>完整URL: {{ getImageUrl(scope.row.cover) }}</p>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="展览时间">
        <template #default="scope">
          {{ formatDateTime(scope.row.startTime) }} 至 {{ formatDateTime(scope.row.endTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
            {{ scope.row.status === 1 ? '已上架' : '已下架' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button
            size="small"
            @click="editExhibition(scope.row.id)"
          >
            编辑
          </el-button>
          <el-button
            size="small"
            type="danger"
            @click="deleteExhibition(scope.row.id)"
          >
            删除
          </el-button>
          <el-button
            size="small"
            :type="scope.row.status === 1 ? 'warning' : 'success'"
            @click="toggleStatus(scope.row)"
          >
            {{ scope.row.status === 1 ? '下架' : '上架' }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <div class="pagination">
      <el-pagination
        background
        layout="prev, pager, next"
        :total="total"
        :current-page="currentPage"
        :page-size="pageSize"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Picture as IconPicture } from '@element-plus/icons-vue'
import { getExhibitionList, deleteExhibition as deleteExhibitionApi, updateExhibitionStatus } from '@/api/exhibition'
import { getImageUrl } from '@/api/file'

const router = useRouter()
const loading = ref(false)
const exhibitionList = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const debugMode = ref(false) // 调试模式

// 格式化日期时间
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return '';
  try {
    const date = new Date(dateTimeStr);
    if (isNaN(date.getTime())) {
      return dateTimeStr;
    }
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
  } catch (error) {
    console.error('日期格式化错误:', error);
    return dateTimeStr;
  }
}

// 获取展览列表
const fetchExhibitionList = async () => {
  loading.value = true
  try {
    const res = await getExhibitionList({
      page: currentPage.value,
      size: pageSize.value
    })
    console.log('API响应:', res)
    if (res.code === 200) {
      exhibitionList.value = res.data.records || []
      total.value = res.data.total || 0
    } else {
      ElMessage.error(res.message || '获取展览列表失败')
    }
  } catch (error) {
    console.error('获取展览列表失败', error)
    ElMessage.error('获取展览列表失败')
  } finally {
    loading.value = false
  }
}

// 页面加载时获取数据
onMounted(() => {
  fetchExhibitionList()
})

// 分页变化
const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchExhibitionList()
}

// 新增展览
const addExhibition = () => {
  router.push('/exhibition/add')
}

// 编辑展览
const editExhibition = (id) => {
  router.push(`/exhibition/edit/${id}`)
}

// 删除展览
const deleteExhibition = (id) => {
  ElMessageBox.confirm('确定要删除该展览吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteExhibitionApi(id)
      ElMessage.success('删除成功')
      fetchExhibitionList()
    } catch (error) {
      console.error('删除展览失败', error)
      ElMessage.error('删除展览失败')
    }
  }).catch(() => {})
}

// 切换展览状态
const toggleStatus = async (row) => {
  const newStatus = row.status === 1 ? 0 : 1
  const statusText = newStatus === 1 ? '上架' : '下架'
  
  try {
    await updateExhibitionStatus(row.id, newStatus)
    ElMessage.success(`${statusText}成功`)
    fetchExhibitionList()
  } catch (error) {
    console.error(`${statusText}失败`, error)
    ElMessage.error(`${statusText}失败`)
  }
}
</script>

<style scoped>
.exhibition-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  align-items: center;
}

.debug-switch {
  margin-right: 10px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.image-container {
  display: flex;
  flex-direction: column;
}

.image-error {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 80px;
  height: 80px;
  background-color: #f5f7fa;
}

.small-text {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
}

.image-debug {
  margin-top: 4px;
  padding: 4px;
  background-color: #f8f9fb;
  border-radius: 4px;
  font-size: 10px;
  color: #606266;
  max-width: 180px;
  word-break: break-all;
}
</style> 